package com.feihong.yw189.activity.yonghuzhongxin;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.SDCardUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.dtr.settingview.lib.SettingView;
import com.dtr.settingview.lib.entity.SettingData;
import com.dtr.settingview.lib.entity.SettingViewItemData;
import com.dtr.settingview.lib.item.BasicItemViewH;
import com.dtr.settingview.lib.item.SwitchItemView;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.MyActivityManager;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.denglu.DengLuActivity;
import com.feihong.yw189.activity.kaika.moneyout.BundingActivity;
import com.feihong.yw189.activity.kaika.moneyout.ShiMingActivity;
import com.feihong.yw189.activity.kaika.moneyout.ShiMingSucActivity;
import com.feihong.yw189.activity.yonghuzhongxin.userinfo.ChangeLoginActivity;
import com.feihong.yw189.activity.yonghuzhongxin.userinfo.ChangePhoneActivity;
import com.feihong.yw189.activity.yonghuzhongxin.userinfo.PayMoneyPassWordActivity;
import com.feihong.yw189.activity.yonghuzhongxin.userinfo.UserInfoEditActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.bluetooth.utils.util.ConstantsValue;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.User.UserEntity;
import com.feihong.yw189.model.User.my.UserImgUpload;
import com.feihong.yw189.utils.CacheDataManger;
import com.feihong.yw189.utils.CustomServiceUtil;
import com.feihong.yw189.utils.MessageEvent;
import com.feihong.yw189.utils.PhotoUtils;
import com.feihong.yw189.utils.PreferenceTools;
import com.feihong.yw189.utils.UserLoginInfo;
import com.feihong.zhiwenlibrary.dialog.DJLM_PasswordDialog;
import com.feihong.zhiwenlibrary.dialog.PasswordDialogListener;
import com.feihong.zhiwenlibrary.zhiwen.ZhiWenCallBack;
import com.feihong.zhiwenlibrary.zhiwen.ZhiWenDialog;
import com.meiqia.meiqiasdk.imageloader.MQImage;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;
import de.hdodenhof.circleimageview.CircleImageView;
import lib.image.compress.TuPianYaSuoTools;
import lib.image.compress.YaSuoListener;
import me.shaohui.bottomdialog.BaseBottomDialog;
import me.shaohui.bottomdialog.BottomDialog;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import txgw.feihong.com.txgwlibrary.mqglide_loader.MQGlideImageLoader4;



@RuntimePermissions
public class MySettingActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.my_setting_title)
    TextView mySettingTitle;
    @BindView(R.id.my_setting_photo)
    CircleImageView mySettingPhoto;
    @BindView(R.id.setting_view_basic_item_h_arrow)
    ImageView settingViewBasicItemHArrow;
    @BindView(R.id.my_setting_photoEdit)
    LinearLayout mySettingPhotoEdit;
    @BindView(R.id.setting_userInfo)
    SettingView settingUserInfo;
    @BindView(R.id.setting_userSoft)
    SettingView settingUserSoft;
    @BindView(R.id.setting_clearData)
    SettingView settingClearData;
    @BindView(R.id.iv_confirm)
    TextView ivConfirm;
    @BindView(R.id.my_setting_exit_btn)
    Button mySettingExitBtn;
    @BindView(R.id.setting_bund)
    SettingView settingBund;

    private SettingData mItemData = null;
    private SettingViewItemData mItemViewData = null;
    private List<SettingViewItemData> mListData = new ArrayList<SettingViewItemData>();
    private List<SettingViewItemData> mListSoftData = new ArrayList<SettingViewItemData>();
    private List<SettingViewItemData> mbundData = new ArrayList<SettingViewItemData>();
    BaseBottomDialog dialog = null;

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private File fileUri = null;
    private Uri imageUri;
    private int photoType = 0; //0拍照 1相册

    private Context mContext;
    private Unbinder unbinder;
    private String mAlipayAccount;
    private String mBankCardNum;
    private SwitchItemView mSwitchItemView;//指纹支付
    ZhiWenDialog zhiWenDialog;
    private File touxiang;
    private String mUserVerfySign = "0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_setting);
        mContext = getActivity();
        unbinder = ButterKnife.bind(this);


        //如果有注册就不注册了
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        zhiWenDialog = new ZhiWenDialog();
        zhiWenDialog.init(getActivity());

        setBackButtonFinish();
        setPageTitle("设置");
        ivLin.setVisibility(View.GONE);
        initView();
        bindData();

    }

    @Override
    public void setTheme() {

    }

    @Override
    public void windowStyle() {
        super.windowStyle();
    }

    UserEntity userEntity;

    @Override
    protected void onResume() {
        super.onResume();

        userEntity = UserLoginInfo.getUserLoginInfoInstance().getUserLoc();
        mAlipayAccount = userEntity.getUserAliPayAccount();
        mBankCardNum = userEntity.getUserBankNum();
        mUserVerfySign = userEntity.getUserVerifyRealNameSign();
        if ("0".equals(mUserVerfySign)) {
            settingBund.modifySubTitle("未认证", 2);
        } else {
            settingBund.modifySubTitle("已认证", 2);
        }

        if (TextUtils.isEmpty(mAlipayAccount)) {
            settingBund.modifySubTitle("未绑定", 0);
        } else {
            settingBund.modifySubTitle("已绑定", 0);
        }

        if (TextUtils.isEmpty(mBankCardNum)) {
            settingBund.modifySubTitle("未绑定", 1);
        } else {
            settingBund.modifySubTitle("已绑定", 1);
        }

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    public void initView() {

        progressDialog = new MyUsualyDialog(MySettingActivity.this, R.layout.wait_item);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        userEntity = UserLoginInfo.getUserLoginInfoInstance().getUserLoc();
        mAlipayAccount = userEntity.getUserAliPayAccount();
        mBankCardNum = userEntity.getUserBankNum();
        mUserVerfySign = userEntity.getUserVerifyRealNameSign();

        mItemData = new SettingData();
        mItemData.setTitle("用户名");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);

        String userName = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserName();
        if (!TextUtils.isEmpty(userName)) {
            mItemData.setSubTitle(userName);
        } else {
            mItemData.setSubTitle("未知");
        }

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("手机号");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);

        String userPhone = UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserMobile();
        if (!TextUtils.isEmpty(userPhone)) {
            userPhone = userPhone.substring(0, 3) + "****" + userPhone.substring(7);
            mItemData.setSubTitle(userPhone);
        } else {
            mItemData.setSubTitle("未知");
        }

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        settingUserInfo.setAdapter(mListData);

        mItemData = new SettingData();
        mItemData.setTitle("登录密码");
        mItemData.setTitleSize(14);

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListSoftData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("支付密码");
        mItemData.setTitleSize(14);

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListSoftData.add(mItemViewData);

        if (zhiWenDialog != null && zhiWenDialog.isFingerprintEnable())
        //  if (1 == 1)
        {


            mItemData = new SettingData();
            mItemData.setTitle("指纹支付");
            mItemData.setTitleSize(14);
            mItemData.setSubTitle("");
            mItemData.setSubTitleSize(12);
            // 指纹 面部android暂时不做  ios初期不做  后期待确认
            mItemViewData = new SettingViewItemData();
            mItemViewData.setData(mItemData);
            mSwitchItemView = new SwitchItemView(getActivity());
            mItemViewData.setItemView(mSwitchItemView);
            mListSoftData.add(mItemViewData);
        } else {
//            mItemData = new SettingData();
//            mItemData.setTitle("指纹支付");
//            mItemData.setTitleSize(16);
//            mItemData.setSubTitle("不支持指纹功能或者没有录入指纹");
//            mItemData.setSubTitleSize(14);
//            // 指纹 面部android暂时不做  ios初期不做  后期待确认
//            mItemViewData = new SettingViewItemData();
//            mItemViewData.setData(mItemData);
//            mItemViewData.setItemView(new BasicItemViewH(getActivity()));
//            mListSoftData.add(mItemViewData);
        }


        mItemData = new SettingData();
        mItemData.setTitle("面部ID");
        mItemData.setTitleSize(14);
        mItemData.setSubTitle("5");
        mItemData.setSubTitleSize(12);

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
//        mListSoftData.add(mItemViewData);

        settingUserSoft.setAdapter(mListSoftData);

        try {
            if (mSwitchItemView.getmSwitch() != null) {
                mSwitchItemView.getmSwitch().changedState(PrefUtils.getBoolean(MySettingActivity.this, ConstantsValue.ZHIWEN_STATE, false));
            }
        } catch (Exception ex) {
        }
//=========================================================================================
        mItemData = new SettingData();
        mItemData.setTitle("绑定支付宝");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);

        if (TextUtils.isEmpty(mAlipayAccount)) {
            mItemData.setSubTitle("未绑定");
        } else {
            mItemData.setSubTitle("已绑定");
        }

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mbundData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("绑定银行卡");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);

        if (TextUtils.isEmpty(mBankCardNum)) {
            mItemData.setSubTitle("未绑定");
        } else {
            mItemData.setSubTitle("已绑定");
        }

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mbundData.add(mItemViewData);

        mItemData = new SettingData();
        mItemData.setTitle("实名认证");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);


        if ("0".equals(mUserVerfySign)) {
            mItemData.setSubTitle("未认证");
        } else {
            mItemData.setSubTitle("已认证");
        }

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mbundData.add(mItemViewData);

        settingBund.setAdapter(mbundData);

//=========================================================================================

        mItemData = new SettingData();
        mItemData.setTitle("清除本地缓存");
        mItemData.setTitleSize(14);
        try {
            mItemData.setSubTitle(CacheDataManger.getTotalCacheSize(MySettingActivity.this));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mItemData.setSubTitleSize(12);

        mItemViewData = new SettingViewItemData();
        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        List<SettingViewItemData> mListClearData = new ArrayList<SettingViewItemData>();
        mListClearData.add(mItemViewData);

        settingClearData.setAdapter(mListClearData);
        settingBund.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {
                if (isFastDoubleClick(SettinglastClickTime)) {
                    return;
                }
                SettinglastClickTime = System.currentTimeMillis();

                switch (index) {
                    case 0: // 支付宝
                        Intent intent4 = new Intent(MySettingActivity.this, BundingActivity.class);
                        intent4.putExtra("bd_type", "0");
                        intent4.putExtra("set_type", "0");
                        startActivity(intent4);
                        break;
                    case 1: // 银行卡
                        Intent intent5 = new Intent(MySettingActivity.this, BundingActivity.class);
                        intent5.putExtra("bd_type", "1");
                        intent5.putExtra("set_type", "0");
                        startActivity(intent5);
                        break;
                    case 2: // 实名认证
                        // 实名认证
                        if ("0".equals(mUserVerfySign)) {
                            Intent intent6 = new Intent(MySettingActivity.this, ShiMingActivity.class);
                            startActivity(intent6);
                        } else {
                            Intent intent6 = new Intent(MySettingActivity.this, ShiMingSucActivity.class);
                            startActivity(intent6);
                        }
                        break;

                }
            }
        });

        // settingview的点击事件
        settingUserInfo.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {
                if (isFastDoubleClick(SettinglastClickTime)) {
                    return;
                }
                SettinglastClickTime = System.currentTimeMillis();
                switch (index) {
                    case 0:
                        //昵称
                        // intent.putExtra("type", 0);
                        showErrorToast("暂不允许更换!");
                        break;
                    case 1:
                        //手机
                        Intent intent = new Intent(mContext, ChangePhoneActivity.class);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        });

        // settingview的点击事件
        settingUserSoft.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {
                if (isFastDoubleClick(SettinglastClickTime)) {
                    return;
                }
                SettinglastClickTime = System.currentTimeMillis();
                Intent mIntent = null;
                switch (index) {
                    case 0:
                        //登录密码
                        mIntent = new Intent(mContext, ChangeLoginActivity.class);
                        mIntent.putExtra("type", 2);
                        break;
                    case 1:
                        //支付密码
                        mIntent = new Intent(mContext, PayMoneyPassWordActivity.class);
                        mIntent.putExtra("type", 3);
                        break;
                    case 2:
                        //指纹设置
                        // mIntent = new Intent(mContext, UserInfoEditActivity.class);
                        //mIntent.putExtra("type", 4);
                        //zhiwen();
                        return;
                    case 3:
                        //面部id
                        mIntent = new Intent(mContext, UserInfoEditActivity.class);
                        mIntent.putExtra("type", 5);
                        break;
                    default:
                        break;
                }
                startActivity(mIntent);
            }
        });

        // settingview的点击事件
        settingClearData.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {
                if (isFastDoubleClick(SettinglastClickTime)) {
                    return;
                }

                SettinglastClickTime = System.currentTimeMillis();
                CacheDataManger.clearAllCache(MySettingActivity.this);
                try {
                    if (CacheDataManger.getTotalCacheSize(MySettingActivity.this).startsWith("0")) {
                        settingClearData.modifySubTitle("0KB", 0);
                        showToast("清理缓存成功");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        if (mSwitchItemView != null) {
            mSwitchItemView.setOnSwitchItemChangedListener(new SwitchItemView.onSwitchItemChangedListener() {
                @Override
                public void onSwitchItemChanged(boolean isChecked) {
                    //  if (mSwitchItemView.getmSwitch().isPressed())
                    {
                        mSwitchItemView.getmSwitch().changedState((isChecked == true ? false : true));
                        zhiwen(isChecked);
                    }

                }
            });
        }


    }

    private void guanbizhiwen() {
        //先弹出指纹验证对话框，成功了，请求服务端关闭
        zhiWenDialog.setZhiWenCallBack(new ZhiWenCallBack() {
            @Override
            public void onSuccess() {
                showToast("指纹验证成功!");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        guanbiZhiWenSubmitServer();//指纹验证成功后，输入支付密码
                    }
                }, 500);
            }

            @Override
            public void onError(String msg) {
                showToast("指纹验证失败:" + msg);
            }

            @Override
            public void onShowPwdDialog() {
                showToast("选择密码支付");
            }
        });
        zhiWenDialog.show(getSupportFragmentManager(), "关闭指纹支付");

    }

    MyUsualyDialog progressDialog;

    DJLM_PasswordDialog mimaDialog;

    private int progressDialog_warningtv_id = R.id.progress_layout_warning_tv;

    private void guanbiZhiWenSubmitServer() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = new MyUsualyDialog(MySettingActivity.this, R.layout.wait_item);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
        progressDialog.setWarningTxt(progressDialog_warningtv_id, "指纹保存中");
        String touch_pwd = PrefUtils.getString(MySettingActivity.this, ConstantsValue.ZHIWEN_KEY, "");
        new HttpTools().openFinger(this, touch_pwd, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    progressDialog.dismiss();
                    JSONObject json = new JSONObject(result);
                    if (json.getInt("status") == 1) {
                        PrefUtils.setString(MySettingActivity.this, ConstantsValue.ZHIWEN_KEY, "");
                        PrefUtils.setBoolean(MySettingActivity.this, ConstantsValue.ZHIWEN_STATE, false);
                        mSwitchItemView.getmSwitch().changedState(false);

                        //              mSwitchItemView.getmSwitch();
                        showToast("关闭成功！");
                    } else {
                        showToast(json.getString("info"));
                    }
                } catch (Exception e) {
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (activityIsDestory()) {
                    return;
                }
                progressDialog.dismiss();
                showToast("网络或服务器错误");
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void zhiwen(boolean isChecked) {
        //先设置原始状态
//        mSwitchItemView.getmSwitch().changedState(!isChecked);
//        mSwitchItemView.getmSwitch();
        if (isChecked) {
            zhiWenDialog.setZhiWenCallBack(new ZhiWenCallBack() {
                @Override
                public void onSuccess() {
                    showToast("指纹验证成功!");
                    zhiWenDialog.dismiss();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            //指纹验证成功后，输入支付密码
                            yanzhengmima();
                        }
                    }, 500);
                }

                @Override
                public void onError(String msg) {
                    showToast("指纹验证失败:" + msg);
                }

                @Override
                public void onShowPwdDialog() {
                    showToast("选择密码支付");
                }
            });
            zhiWenDialog.show(getSupportFragmentManager(), "开启指纹支付");
        } else {
            //关闭
            //ToastUtils.showShort( "关闭指纹支付功能！");
            guanbizhiwen();

        }

    }

    /**
     * 输入完支付密码后，验证支付密码获取密钥
     */
    private void yanzhengmima() {
        mimaDialog = new DJLM_PasswordDialog(MySettingActivity.this);
        mimaDialog.setEnableFinger(false);
        mimaDialog.setCallBack(new PasswordDialogListener() {
            @Override
            public void onDoneInput(DJLM_PasswordDialog dialog, final String pwd) {
                //密码输入完成
                //mimaDialog.dismiss();
                mimaDialog.showLoadingView();
                mimaDialog.setState(R.mipmap.wait, "正在验证...");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getZhiWenKey(pwd);
                    }
                }, 1000);
            }

            @Override
            public void successFinger(DJLM_PasswordDialog dialog) {
            }

            @Override
            public void onBtnClick(int type) {
                if (type == 1) {
                    //加宽按钮点击
                    // startActivity(new Intent(MySettingActivity.this, AddMoneyActivity.class));
                } else if (type == 2) {
                    //忘记密码按钮点击
                    //   startActivity(new Intent(MySettingActivity.this, ForgetPwdActivity.class));
                }/*else if(type == 3){
                   if(mimaDialog != null){
                       mimaDialog.dismiss();
                   }
                }*/
            }
        });
        mimaDialog.show(getSupportFragmentManager(), "支付密码");
    }

    private static final String TAG = "指纹";

    private void getZhiWenKey(String pwd) {

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
        progressDialog = new MyUsualyDialog(MySettingActivity.this, R.layout.wait_item);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        new HttpTools().openFinger(this, pwd, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                try {
                    JSONObject json = new JSONObject(result);
                    if (json.getInt("status") == 1) {
                        String touch_pwd = json.getJSONObject("data").getString("touch_pwd");
                        if (!TextUtils.isEmpty(touch_pwd)) {
                            PrefUtils.setString(MySettingActivity.this, ConstantsValue.ZHIWEN_KEY, touch_pwd);
                            PrefUtils.setBoolean(MySettingActivity.this, ConstantsValue.ZHIWEN_STATE, true);
                            mSwitchItemView.getmSwitch().changedState(true);

                            mimaDialog.setState(R.mipmap.pay_su, "开启成功！");
                            mHandler.sendMessageDelayed(mHandler.obtainMessage(1), 3000);
                        } else {

                            //                       mSwitchItemView.getmSwitch().changedState(false);
                            mimaDialog.setState(R.mipmap.pay_er, "开启失败，服务端返回的数据不正确！");
                            mHandler.sendMessageDelayed(mHandler.obtainMessage(1), 3000);
                        }
                    } else {
                        //              mSwitchItemView.getmSwitch().changedState(false);

                        mimaDialog.setState(R.mipmap.pay_er, json.getString("info"));
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(1), 3000);
                    }
                } catch (Exception e) {
                    if (mimaDialog != null) {
                        mimaDialog.dismiss();
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                showToast("网络或服务器错误");
                if (mimaDialog != null) {
                    mimaDialog.dismiss();
                }
            }

            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }


    public void bindData() {
        //头像
        Glide.with(mContext).load(UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserPic()).apply(new RequestOptions().placeholder(R.mipmap.my_setting_photo)).into(mySettingPhoto);

    }

    @Override
    @OnClick({R.id.txt_pagetitle, R.id.iv_lin, R.id.top_back_layout, R.id.setting_userInfo, R.id.setting_userSoft, R.id.my_setting_photoEdit, R.id.my_setting_exit_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_pagetitle:
                break;
            case R.id.iv_lin:
                CustomServiceUtil customServiceUtil = new CustomServiceUtil();
                MQImage.setImageLoader(new MQGlideImageLoader4());
                Intent customeServiceIntent = new MQIntentBuilder(this)
                        .setClientInfo(customServiceUtil.queryConfig())
                        .build();
                startActivity(customeServiceIntent);
                break;
            case R.id.top_back_layout:
                break;
            case R.id.my_setting_photoEdit:
                dialogChoose();
                break;
            case R.id.user_take_photo:
                photoType = 0;
                dialog.dismiss();
                //fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");

                takePhoto();
                break;
            case R.id.user_select_from_lib:
                photoType = 1;
                dialog.dismiss();
                MySettingActivityPermissionsDispatcher.openCameraWithCheck(this);
                //imageUri = Uri.fromFile(fileUri);

                break;
            case R.id.user_photo_cancel:
                dialog.dismiss();
                break;
            //登录/退出
            case R.id.my_setting_exit_btn:
                mySettingExitBtn.setEnabled(false);
                exitBtn();
                break;
            default:
                break;
        }
    }

    private void exitBtn() {
        //显示登录提示
        showConfirmDialog("", "是否退出登录", "确认", "取消",
                new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        progressDialog.show();
                        progressDialog.setWarningTxt(progressDialog_warningtv_id, "正在退出");
                        //showToast("正在退出,请稍后...");
                        Callback.Cancelable cancelOut = App.getApp().getHttpTools().exitLogin(new RequestCallBack() {
                            @Override
                            public void onSuccess(Object result) {
                            }

                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                            }

                            @Override
                            public void onCancelled(Callback.CancelledException cex) {
                            }

                            @Override
                            public void onFinished() {
                                progressDialog.dismiss();
                                //暂时用的方法是清空token
                                UserLoginInfo.getUserLoginInfoInstance().updateUserToken("");
                                UserLoginInfo.getUserLoginInfoInstance().clearUserInfo();
                                PreferenceTools.clear();
                                Intent intent = new Intent(getActivity(), DengLuActivity.class);
                                getActivity().startActivity(intent);
                                MyActivityManager.finishAll();
                            }
                        });
                        RequestTools.addNewRequest(MySettingActivity.class.getName(), cancelOut);
                    }
                }, sweetAlertDialog -> {
                    mySettingExitBtn.setEnabled(true);
                    sweetAlertDialog.dismiss();
                });
    }

    //拍照相册选择dialog
    private void dialogChoose() {
        dialog = BottomDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.activity_my_photo_edit)
                .setDimAmount(0.5f)            // Dialog window 背景色深度 范围：0 到 1，默认是0.2f
                .setCancelOutside(false)     // 点击外部区域是否关闭，默认true
                .setTag("BottomDialog")     // 设置DialogFragment的tag
                .setViewListener(new BottomDialog.ViewListener() {      // 可以进行一些必要对View的操作
                    @Override
                    public void bindView(View v) {
                        dialogClick(v);
                    }
                })
                .show();
    }

    private void dialogClick(View v) {
        v.findViewById(R.id.user_take_photo).setOnClickListener(this);

        v.findViewById(R.id.user_select_from_lib).setOnClickListener(this);

        v.findViewById(R.id.user_photo_cancel).setOnClickListener(this);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void openCamera() {
        switch (photoType) {
            case 0:
                PhotoUtils.takePicture(this, fileUri, CODE_CAMERA_REQUEST);
                break;
            case 1:
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                break;
            default:
                break;
        }
    }

    private void takePhoto() {
        try {
            String sdCardPath = SDCardUtils.getSDCardPathByEnvironment();
            if (TextUtils.isEmpty(sdCardPath)) {
                showErrorToast("SD卡不可用，请检查权限是否给全！");
                return;
            }
            File dirPath = new File(sdCardPath + "/YW189/");
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            File filePath = null;
            filePath = new File(dirPath.getAbsolutePath() + "/touxiang.jpg");
            if (filePath == null) {
                return;
            }
            fileUri = filePath;
            imageUri = Uri.fromFile(fileUri);

            MySettingActivityPermissionsDispatcher.openCameraWithCheck(this);
        } catch (Exception ex) {
            ex.printStackTrace();
            showErrorToast("出错：无法创建制定的文件夹，请重试！");
        }

    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MySettingActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void denied() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void askAgain() {
        showErrorDialog("权限不足", "您没有开启此应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方应用管家（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    public static String getFilePathFromContentUri(Uri selectedVideoUri,
                                                   ContentResolver contentResolver) {
        String filePath;
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
//      也可用下面的方法拿到cursor
//      Cursor cursor = this.context.managedQuery(selectedVideoUri, filePathColumn, null, null, null);

        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            File file = null;

            switch (requestCode) {

                case CODE_CAMERA_REQUEST://拍照完成回调
                    if (imageUri != null) {
                        try {
                            file = new File(new URI(imageUri.toString()));
                        } catch (Exception e) {
                            showErrorToast("获取文件失败");
                            e.printStackTrace();
                        }
                    } else {
                        showErrorToast("图片保存路径为空");
                    }
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (PhotoUtils.hasSdcard()) {
                        String path = PhotoUtils.handleImageOnKitKat(MySettingActivity.this, data);
                        file = new File(path);
                    } else {
                        showErrorToast("设备没有SD卡!");
                        return;
                    }
                    break;
            }
            //裁剪结果 -> 鲁班压缩
            if (file == null) {
                showErrorToast("图片获取失败");
                return;
            }
            progressDialog.show();
            progressDialog.setWarningTxt(progressDialog_warningtv_id, "图片处理中");
            /**压缩优化*/
            TuPianYaSuoTools tuPianYaSuoTools = new TuPianYaSuoTools();
            String outputPath = getExternalCacheDir().getAbsolutePath() + "/headImg.jpg";
            try {
                tuPianYaSuoTools.YaSuo(file.getAbsolutePath(), outputPath, new YaSuoListener() {
                    @Override
                    public void success(String outputfile) {

                        File file = new File(outputfile);
                        if (file != null && file.exists()) {
                            Callback.Cancelable cancelable = App.getApp().getHttpTools().uploadImgFile(file, commonCallback);
                            RequestTools.addNewRequest(MySettingActivity.class.getName(), cancelable);
                        } else {
                            showErrorToast("图片保存失败");
                        }
                    }

                    @Override
                    public void error(String error) {
                        progressDialog.dismiss();
                        showErrorToast("图片保存失败");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    //EventBus 回调通知,修改设置信息
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        switch (event.getType()) {
            case MessageEvent.EDIT_NAME:
                settingUserInfo.modifySubTitle(UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserName(), 0);
                break;
            case MessageEvent.EDIT_PHONE:
                settingUserInfo.modifySubTitle(UserLoginInfo.getUserLoginInfoInstance().getUserLoc().getUserMobile(), 1);
                break;
            default:
                break;
        }
    }

    RequestCallBack<String> commonCallback = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            try {

                UserImgUpload jsonMess = JSON.parseObject(result, UserImgUpload.class);
                if (jsonMess != null) {
                    if (jsonMess.getStatus() == 1) {
                        String simpleUri = jsonMess.getData().getUrl();
                        //更新本地地址
                        UserLoginInfo.getUserLoginInfoInstance().setUserPic(simpleUri);
                        //通知
                        EventBus.getDefault().postSticky(new MessageEvent(MessageEvent.EDIT_PHOTO));
                        //设置头像显示
                        Glide.with(mContext).load(simpleUri).into(mySettingPhoto);
                    } else {
                        showErrorToast(jsonMess.getInfo());
                    }
                } else {
                    showErrorToast(TAG + "服务器返回数据为空");
                }
            } catch (Exception ex) {
                showErrorToast(TAG + "数据解析异常");
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            showErrorToast("网络或服务器错误");
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {
            if (progressDialog != null) {
                progressDialog.dismiss();
            }
        }
    };

    private static long SettinglastClickTime;
    private static long OtherlastClickTime;

    private static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000 * 2) {
            return true;
        }
        return false;
    }

    @Override
    public void setBackButtonFinish() {
        if (ivBack != null) {
            ivBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RequestTools.removeRequest(MySettingActivity.class.getName());
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    private Handler mHandler = new Handler() {

        public void dispatchMessage(Message msg) {
            if (1 == msg.what) {
                if (mimaDialog != null) {
                    mimaDialog.dismiss();
                }
            }
        }

        ;
    };

}
